import { getStoredDirectoryHandle, storeDirectoryHandle } from './smap-filehandles-store';
import * as fs from './fs-helpers';
import type { IDBHandles } from './types';

export const dbInfo = {
  name: 'smap-web-db',
  version: 1,
  tables: {
    filehandles: 'smap-filehandles-store',
  },
};

const handleStore: Record<string, IDBHandles> = {};

export const getHandles = async (id: string): Promise<IDBHandles> => {
  try {
    if (handleStore[id]) return handleStore[id];
    let dbFileHandle = await getStoredDirectoryHandle();
    if (!dbFileHandle) {
      const fileHandle = await fs.getDirectoryHandle();
      if (!(await fs.verifyPermission(fileHandle, true))) throw new Error('未获取到数据库句柄');
      dbFileHandle = await storeDirectoryHandle(fileHandle);
    } else {
      if (!(await fs.verifyPermission(dbFileHandle, true))) throw new Error('未获取到数据库句柄');
    }
    const root = await dbFileHandle.getDirectoryHandle(id, { create: true });
    const data = await root.getDirectoryHandle('data', { create: true });
    const manifest = await root.getFileHandle('manifest.json', { create: true });
    handleStore[id] = { root, data, manifest };
    return handleStore[id];
  } catch (e) {
    console.error(e);
    throw e;
  }
};
